package org.scboy.gateway.init;

import java.io.File;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

import org.apache.dubbo.config.annotation.DubboReference;
import org.scboy.dbms.api.AppManager;
import org.scboy.gateway.utils.JarPathUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import cn.hutool.core.io.FileUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import jakarta.annotation.PostConstruct;

@Configuration
public class AppInit {

	Log log=LogFactory.get();
	
	@Value("${spring.application.name}")
	String appName;

	@Value("${server.port}")
	int port;
	
	@DubboReference
	AppManager app;
	
	@PostConstruct
	public void init() {
		String ip="";
		String deploymentPath = JarPathUtil.getLocation();
		try {
			InetAddress localHost=InetAddress.getLocalHost();
			ip=localHost.getHostAddress();
		} catch (UnknownHostException e) {
			log.error("无法获取服务器IP地址",e);
		}
		
		String config="";
		
		String docType="properties";
		
		String currentDir = JarPathUtil.getLocation();
		
		//检查外部properties配置
		File properties= new File(currentDir+"config/application.properties");
		
		//检查外部YML配置
		File yml= new File(currentDir+"config/application.yml");
		
		if(properties.exists()) {
			config=FileUtil.readUtf8String(properties);
			docType="properties";
		}else if(yml.exists()) {
			config=FileUtil.readUtf8String(yml);
			docType="yml";
		}else {
			URL urlProperties=AppInit.class.getClassLoader().getResource("application.properties");
			URL urlYml=AppInit.class.getClassLoader().getResource("application.yml");
			
			if(urlProperties!=null) {
				config=FileUtil.readString(urlProperties, Charset.defaultCharset());
				docType="properties";
			}else if(urlYml!=null) {
				config=FileUtil.readString(urlYml, Charset.defaultCharset());
				docType="yml";
			}
		}
		
		app.register(ip, port, appName, deploymentPath,config,docType);
	}
}
